package com.by.hellospringboot.service.impl;

import com.by.hellospringboot.domain.User;
import com.by.hellospringboot.domain.repository.UserRepository;
import com.by.hellospringboot.exception.UnAuthorizedException;
import com.by.hellospringboot.service.TestUserService;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.sql.SQLException;
import java.util.List;

@Service
public class TestUserServiceImpl implements TestUserService {

    private final UserRepository userRepository;

    public TestUserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    
    @Override
    public User create() {
        //insert into jpa_user (access_card_number, age, gender, phone, username) values (?, ?, ?, ?, ?)
        User user = new User();
        user.setUsername("test");
        user.setPhone("13112345678");
        user.setAge(18);
        user.setGender(0);
        user.setAccessCardNumber("ic_001");
        return userRepository.save(user);
    }

    @Override
    public User findById(Long id) {
        //select user0_.id as id1_0_0_, user0_.access_card_number as access_c2_0_0_, user0_.age as age3_0_0_, user0_.gender as gender4_0_0_, user0_.phone as phone5_0_0_, user0_.username as username6_0_0_ from jpa_user user0_ where user0_.id=?
        return userRepository.findById(id).orElse(null);
    }

    @Override
    public User update() {
        //update jpa_user set access_card_number=?, age=?, gender=?, phone=?, username=? where id=?
        User user = findById(1L);
        user.setPhone("13212345678");
        return userRepository.save(user);
    }

    @Override
    public List<User> list() {
        //select user0_.id as id1_0_, user0_.access_card_number as access_c2_0_, user0_.age as age3_0_, user0_.gender as gender4_0_, user0_.phone as phone5_0_, user0_.username as username6_0_ from jpa_user user0_ where (user0_.age between ? and ?) and user0_.gender=?
        return userRepository.findByAgeBetweenAndGender(18, 22, 0);
    }

    @Override
    public void delete() {
        //delete from jpa_user where id=?
        userRepository.deleteById(1L);
    }

    @Override
    public void testError(Integer errorCode) {
        if (errorCode == null) {
            return;
        }
        if (errorCode == 401) {
            throw new UnAuthorizedException("登录用户不存在");
        }
        if (errorCode == 500) {
            User user = new User();
            //出发字段不能为空的错误
            userRepository.save(user);
        }

    }

}
